package cn.matrix42.potoo;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {

    public static void main(String[] args) throws IOException {

        File file = new File("D:\\OneDrive - tp.edu.tw\\学习资料\\learning-materials\\博客");
        process(file);
    }

    private static void process(File file) throws IOException {
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            if (files != null) {
                for (File file1 : files) {
                    process(file1);
                }
            }
        }

        if (!file.getAbsolutePath().endsWith("md")) {
            return;
        }

        List<String> contents = new ArrayList<>();

        // 兼容图片路径
        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
            String line;
            while ((line = reader.readLine()) != null) {
                if (line.startsWith("![") || line.startsWith("[![")) {
                    line = line.trim().replaceAll(" ", "%20");
                }
                contents.add(line);
            }
        }

        // trim empty lines to one
        List<String> newContents = new ArrayList<>();
        String pre = null;
        for (String content : contents) {
            if (pre != null && isBlank(content) && isBlank(pre)) {
                continue;
            }
            newContents.add(content);
            pre = content;
        }
        contents = newContents;

        // normalize cnblogs
        Pattern pattern = Pattern.compile("\\\\\\d\\. .*");
        for (int i = 0; i < contents.size(); i++) {
            String content = contents.get(i);
            Matcher matcher = pattern.matcher(content);
            if (matcher.matches()) {
                content = content.replaceFirst("\\\\", "");
                contents.set(i, content);
            }
        }


        try (BufferedWriter writer = new BufferedWriter(new FileWriter(file, false))) {
            for (int i = 0; i < contents.size(); i++) {
                writer.write(contents.get(i));
                if (i != contents.size() - 1) {
                    writer.newLine();
                }
            }
            writer.flush();
        }

    }

    private static boolean isBlank(String content) {
        if (content.length() == 0) {
            return true;
        }
        boolean empty = true;
        for (int i = 0; i < content.length(); i++) {
            char ch = content.charAt(i);
            if (ch == '\r' || ch == '\n' || ch == '\t' || ch == ' ') {
                // ig
            } else {
                empty = false;
            }
        }
        return empty;
    }

}
